import {
  Component,
  ViewChild,
  Injector,
  Output,
  EventEmitter,
  ElementRef
} from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import {
  LocationServiceProxy,
  LocationDto
} from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'createOrEditLocationModal',
  templateUrl: './create-or-edit-location-modal.component.html'
})
export class CreateOrEditLocationModalComponent extends AppComponentBase {
  @ViewChild('createOrEditModal') modal: ModalDirective;

  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  active = false;
  saving = false;
  pid = 0;
  location = new LocationDto();

  constructor(
    injector: Injector,
    private _locationService: LocationServiceProxy
  ) {
    super(injector);
  }

  show(type: number, pid?: number, id?: number): void {
    this.active = true;
    this.pid = pid;
    if (id === 0) {
      id = null;
    }
    this._locationService.getLocationForEdit(type, id).subscribe(result => {
      this.location = result;
      if (type === 2 || type === 3) {
        this.location.parentId = this.pid;
      }
      this.modal.show();
    });
  }

  save(): void {
    this.saving = true;

    this._locationService
      .createOrUpdateLocation(this.location)
      .pipe(finalize(() => (this.saving = false)))
      .subscribe(() => {
        this.notify.info(this.l('SavedSuccessfully'));
        this.close();
        this.modalSave.emit(this.location.type);
      });
  }

  close(): void {
    this.active = false;
    this.modal.hide();
  }
}
